package smokesignals.data.hibernate;

import com.google.common.base.Preconditions;
import com.googlecode.recycled.data.AbstractDataStore;
import com.googlecode.recycled.data.WithId;
import org.hibernate.SessionFactory;

import java.io.Serializable;

/**
 * @author Henryk Konsek
 */
public class HibernateDataStore<T extends Serializable> extends AbstractDataStore<T> {

    protected SessionFactory sessionFactory;

    public HibernateDataStore(SessionFactory sessionFactory) {
        Preconditions.checkNotNull(sessionFactory);
        this.sessionFactory = sessionFactory;

        registerQuerySupport(String.class, new HsqlQueryHandler(sessionFactory));
    }

    @Override
    protected void doDelete(WithId<T> withId) {
        sessionFactory.getCurrentSession().delete(withId);
    }

    @Override
    @SuppressWarnings("unchecked") // Raw Hibernate's Session#load vs generic Persister#load
    protected <V extends WithId<T>> V doLoad(Class<V> clazz, T id) {
        return (V) sessionFactory.getCurrentSession().load(clazz, id);
    }

    @Override
    protected void doStore(WithId<T> withId) {
        sessionFactory.getCurrentSession().saveOrUpdate(withId);
    }

}
